<template>
  <div class="bg">
    <div id="app">
      <h1>userId: {{user}}</h1>
      <input v-model="message" placeholder="Type a message" />
      <button @click="sendMessage">Send</button>
      <p>Received: {{ receivedMessage }}</p>
    </div>
    <br></br>

    <div>
      <!-- 绑定el-avatar的src属性到avatarUrl -->
      <el-avatar shape="square" :size="100" :src="avatarUrl" :key="circleUrl" ></el-avatar>
    </div>
  </div>


</template>

<style>
.bg {
  margin-left: 20px;
  height: 100cqh;
  background-color: white;
}

</style>

<script>
  export default {
    data() {
      return {
        user: 'Test',
        message: '',
        receivedMessage: '',
        socket: null,
        avatarUrl: "https://img1.baidu.com/it/u=2149795385,3590548205&fm=253&fmt=auto&app=138&f=JPEG?w=360&h=360",
      };
    },
    methods: {
      sendMessage() {
        if (this.socket) {
          this.socket.send(this.message);
        }
      },
      initWebSocket() {
        this.socket = new WebSocket("ws://8.153.71.138:8411/sel/websocket/{22}/13412124");
        
        this.socket.onmessage = (event) => {
          this.receivedMessage = event.data;
        };

        this.socket.onopen = () => {
          console.log('WebSocket connection established');
          // 在这里设置请求头，例如：设置一个认证token
          this.socket.send(JSON.stringify({ token: 'your-token-here' }));
        };
  
        this.socket.onclose = () => {
          console.log('WebSocket connection closed');
          // Attempt to reconnect after a delay
        //   setTimeout(this.initWebSocket, 10000);
        };
  
        this.socket.onerror = (error) => {
          console.error('WebSocket error: ', error);
        };
      }
    },
    mounted() {
      this.initWebSocket();
    }
  };
</script>
  
